package cn.tedu.micro.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;
import java.util.regex.Pattern;

//@Component
public class TokenFilter implements GlobalFilter, Ordered {
    //定义一个用于校验token的值的正则表达式
    private static final  String TOKEN_REGEX="\\d{10}";
    //将正则表达式的字符串封装为Pattern对象
    private static final Pattern TOKEN_PATTERN=Pattern.compile(TOKEN_REGEX);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        boolean result = isValid(request);
        if(result){
            //认证通过，放行
            return chain.filter(exchange);
        }else{
            //认证失败,拦截
            String jsonData="{\"state\":200,\"message\":\"无权限访问\",\"data\":null}";
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            byte[] bytes = jsonData.getBytes(StandardCharsets.UTF_8);
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
            Mono<DataBuffer> dataBufferMono = Mono.fromSupplier(new Supplier<DataBuffer>() {
                @Override
                public DataBuffer get() {
                    //返回上面包装好的缓冲流
                    return dataBuffer;
                }
            });
            return response.writeWith(dataBufferMono);
        }
    }

    private boolean isValid(ServerHttpRequest request) {
        //获取请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取name
        List<String> names = queryParams.get("name");
        if(CollectionUtils.isEmpty(names)){
            System.out.println("name没有值");
            return false;
        }
        //获取请求头Authorization
        List<String> authorization = request.getHeaders().get("Authorization");
        if(CollectionUtils.isEmpty(authorization)) {
            System.out.println("Authorization没有值");
            return false;
        }
        //获取Token
        List<String> token = queryParams.get("token");
        return token!=null && !token.isEmpty() && TOKEN_PATTERN.matcher(token.get(0)).matches();
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
